<?php
// ========================== 文件说明 ==========================//
// 本文件说明：缓存管理
// ==============================================================//


if(!defined('IN_ROOT') || !isset($php_self) || !preg_match("/[\/\\\\]index\.php$/", $php_self)) {
	exit('Access Denied');
}

//权限检查
permission();

$url = 'index.php?job=cache';
if ($action == 'updateall') {
	restats();
	redirect('所有缓存已经更新', $url);
}

if ($action == 'delsearchlog') {
	$db->query("TRUNCATE TABLE {$tablepre}xna_search");
	redirect('搜索记录已经清空', $url);
}
	

// 更新首页统计
if ($action == 'dostatsdata') {
	// 更新首页显示的站点数
	$site_count = $db->num($db->query("SELECT siteid FROM {$tablepre}xna_site WHERE state='1'"));
	// 更新首页显示的分类数
	$cate_count = $db->num($db->query("SELECT cid FROM {$tablepre}xna_category"));
	// 更新首页显示的文章数
	$feed_count = $db->num($db->query("SELECT feedid FROM {$tablepre}xna_feed WHERE state!='0'"));
	// 更新首页显示的评论数
	$comment_count = $db->num($db->query("SELECT c.commid FROM {$tablepre}xna_comment c LEFT JOIN {$tablepre}xna_feed a ON (a.feedid=c.feedid) WHERE a.state='1'"));
	// 更新首页显示的用户数
	$user_count = $db->num($db->query("SELECT uid FROM {$tablepre}xna_users"));	
	
	$db->query("UPDATE {$tablepre}xna_statistics SET site_count='$site_count',cate_count='$cate_count',feed_count='$feed_count',comment_count='$comment_count',user_count='$user_count'");
	statistics_recache();
	redirect('首页统计已经更新', 'index.php?job=cache&action=rebuild');
}
// 更新所有分类的文章数
if ($action == 'docatedata') {
	$query = $db->query("SELECT cid, cate_title FROM {$tablepre}xna_category");
	while ($cate = $db->row($query)) {
		$tatol = $db->num($db->query("SELECT feedid FROM {$tablepre}xna_feed WHERE state = '1' AND cid='".$cate['cid']."'"));
		$db->query("UPDATE {$tablepre}xna_category SET feed_count='$tatol' WHERE cid='".$cate['cid']."'");
	}
	categories_recache();
	redirect('所有分类的文章数已经更新', 'index.php?job=cache&action=rebuild');
}
// 更新站点统计数据
if ($action == 'dositedata') {
	$query = $db->query("SELECT siteid FROM {$tablepre}xna_site");
	while ($site = $db->row($query)) {
		$feed_count = $db->num($db->query("SELECT siteid FROM {$tablepre}xna_feed WHERE siteid='".$site['siteid']."'"));
		$db->query("UPDATE {$tablepre}xna_site SET feed_count='$feed_count' WHERE siteid='".$site['siteid']."'");
	}
	sites_recache();
	redirect('所有站点统计数据已经更新', 'index.php?job=cache&action=rebuild');
}
// 重建文章数据
if ($action == 'doarticledata') {
	$step = (!$step) ? 1 : $step;
	$percount = ($percount <= 0) ? 100 : $percount;
	$start    = ($step - 1) * $percount;
	$next     = $start + $percount;
	$step++;
	$jumpurl  = 'index.php?job=cache&action=doarticledata&step='.$step.'&percount='.$percount;
	$goon     = 0;
	$query = $db->query("SELECT feedid FROM {$tablepre}xna_feed ORDER BY feedid LIMIT $start, $percount");
	while ($article = $db->row($query)) {
		$goon = 1;
		// 更新所有文章的评论数
		$tatol = $db->num($db->query("SELECT commid FROM {$tablepre}xna_comment WHERE feedid='".$article['feedid']."' AND state='1'"));
		$db->query("UPDATE {$tablepre}xna_feed SET comments='$tatol' WHERE feedid='".$article['feedid']."'");
	}
	if($goon){
		redirect('正在更新 '.$start.' 到 '.$next.' 项', $jumpurl, '2');
	} else{
		$feed_count = $db->num($db->query("SELECT feedid FROM {$tablepre}xna_feed WHERE state = '1'"));
		$db->query("UPDATE {$tablepre}xna_statistics SET feed_count='$feed_count'");
		statistics_recache();
		redirect('成功重建所有文章数据', 'index.php?job=cache&action=rebuild');
	}
}
// 重建后台用户文章数量
if ($action == 'doadmindata') {
	$query = $db->query("SELECT uid FROM {$tablepre}xna_users WHERE groupid='1' OR groupid='2'");
	while ($user = $db->row($query)) {
		$tatol = $db->num($db->query("SELECT feedid FROM {$tablepre}xna_feed WHERE state='1' AND uid='".$user['uid']."'"));
		$db->query("UPDATE {$tablepre}xna_users SET feed_count='$tatol' WHERE uid='".$user['uid']."'");
	}
	redirect('成功重建所有后台用户数据', 'index.php?job=cache&action=rebuild');
}

if ($action == 'dorewrite') {	
	$db->query("REPLACE INTO {$tablepre}xna_settings VALUES ('rewrite_enable', '1'),('rewrite_ext', '".addslashes($_POST['rewrite_ext'])."')");
	settings_recache();
	redirect('已经开启URL优化功能.', 'index.php?job=cache&action=rewrite_1');
}

if ($action == 'closeurlseo') {
	$db->query("REPLACE INTO {$tablepre}xna_settings VALUES ('rewrite_enable', '0')");
	settings_recache();
	redirect('已经关闭URL优化功能.', 'index.php?job=cache&action=rewrite_1');
}


if ($action == 'update') {

	switch($_GET['id']) {

		case 'links':

			links_recache();

			redirect('友情链接缓存已经更新', $url);

			break;

		case 'newcomments':

			newcomments_recache();

			redirect('侧边栏显示的最新评论缓存已经更新', $url);

			break;

		case 'settings':

			settings_recache();

			redirect('常规选项缓存已经更新', $url);

			break;

		case 'categories':

			categories_recache();

			redirect('侧边栏分类缓存已经更新', $url);

			break;
		case 'statistics':
			statistics_recache();
			redirect('站点统计信息缓存已经更新', $url);
			break;
		case 'sites':
			sites_recache();
			redirect('站点统计缓存已经更新', $url);
			break;
		case 'hottags':
			hottags_recache();
			redirect('侧边栏热门标签缓存已经更新', $url);
			break;
		case 'stylevars':
			stylevars_recache();
			redirect('自定义模板变量缓存已经更新', $url);
			break;

		default:

			redirect('请选择需要更新的缓存', $url);

			break;

	}

}


if(!$action || $action == 'cache') {
	$cachedesc = array(		
		'categories'  => '分类缓存',
		'sites'	  => '站点缓存',
		'hottags'     => '侧边栏热门标签',
		'links'		  => '友情链接',
		'newcomments' => '侧边栏显示的最新评论',

		'settings'    => '常规选项',
		'statistics'  => '站点统计信息',
		'stylevars'   => '自定义模板变量'

	);
	$cachedb = array();
	foreach ($cachedesc AS $name => $desc)	{
		$filepath = '../cache/cache_'.$name.'.php';
		if(is_file($filepath)) {
			$cachefile['name'] = $name;
			$cachefile['desc'] = $desc;
			$cachefile['size'] = filesize($filepath);
			$cachefile['mtime'] = @sadate('Y-m-d H:i',@filemtime($filepath));
			$fp=fopen($filepath,'rb');
			$bakinfo=fread($fp,200);
			fclose($fp);
			$detail=explode("\n",$bakinfo);
			$cachefile['ctime'] = (strlen($detail[2]) == 33) ? substr($detail[2],13,16) : '未知';
			$cachedb[] = $cachefile;
		}
	}
	unset($cachefile);
	$subnav = '缓存管理';
}

// 查看缓存

if ($action == 'show') {
	$name = $_GET['id'];	
	$name = in_array($name, array('sites', 'categories', 'hottags', 'links', 'newcomments', 'settings', 'statistics','stylevars')) ? $name : '';
	if ($name) {
		$filepath = '../cache/cache_'.$name.'.php';
		if(is_file($filepath)) {
			$fp = fopen($filepath,'rb');
			$cachedata = fread($fp,filesize($filepath));
			$cachedata = str_replace("<?php\r\n",'',$cachedata);
			$cachedata = str_replace("\r\nif(!defined('IN_ROOT')) exit('Access Denied');\r\n",'',$cachedata);
			$cachedata = str_replace("\r\n\r\n?>",'',$cachedata);

			ob_start();

			print_r(htmlspecialchars($cachedata));

			$data = ob_get_contents();

			ob_end_clean();
			$subnav = '查看缓存';
		} else {		
			redirect('缓存文件不存在', $url);
		}
	} else {		
		redirect('缓存文件不存在', $url);
	}

}


// 重建数据
if($action == 'rebuild') {
	$subnav = '重建数据';
}//rebuild

if($action == 'searchlog') {
	if($page) {
		$start_limit = ($page - 1) * 30;
	} else {
		$start_limit = 0;
		$page = 1;
	}
	$dodesc = array(
		'article' => '文章',
		'comment' => '评论'
	);
	$searchs  = $db->query("SELECT * FROM {$tablepre}xna_search");
	$tatol     = $db->num($searchs);
	$multipage = multi($tatol, 30, $page, "index.php?job=cache&action=searchlog");
	$searchdb = array();
	$query = $db->query("SELECT * FROM {$tablepre}xna_search ORDER BY searchid DESC LIMIT $start_limit, 30");
	while ($search = $db->row($query)) {
		$search['dateline'] = sadate('Y-m-d H:i',$search['dateline']);
		$search['searchfrom'] = $dodesc[$search['searchfrom']];
		$searchdb[] = $search;
	}//end while
	unset($search);
	$db->free($query);
	$subnav = '搜索记录';
}

if ($action == 'rewrite_1') {
	$query = $db->query("SELECT * FROM {$tablepre}xna_settings WHERE title='rewrite_enable' OR title='rewrite_ext'");
	while($setting = $db->row($query)) {
		$settings[$setting['title']] = htmlspecialchars($setting['value']);
	}
	ifselected($settings['rewrite_enable'],'rewrite_enable');
	$subnav = 'URL静态化';
}

if ($action == 'rewrite_2') {
	//读取rewrite规则源文件
	$rewritefile = _ROOT.'include/htaccess.txt';
	$filecontent = '';
	if(is_readable($rewritefile)) {
		$fp = fopen($rewritefile, 'rb'); 
		$filecontent = fread($fp, filesize($rewritefile));
		fclose($fp);
		$rewrite_ext = $rewrite_ext ? $rewrite_ext : 'html';
		$filecontent = str_replace(array('<IN_ROOT>','<REWRITE_EXT>'),array(dirname(dirname($php_self)),$rewrite_ext),$filecontent);
	} else {
		redirect('rewrite规则源文件不存在', 'index.php?job=cache&action=rewrite_1');
	}
	$filecontent = htmlspecialchars($filecontent);
	$subnav = 'URL静态化';
}

// JS调用
if ($action == 'js') {
	if(!$options['js_enable']) {
        redirect('系统JS调用功能尚未启用,请到系统设置开启', 'index.php?job=configurate&type=js');
	}
	$view = in_array($_POST['view'], array('article', 'stat')) ? $_POST['view'] : '';
	$orderby = in_array($_POST['orderby'], array('dateline', 'views', 'comments')) ? $_POST['orderby'] : 'dateline';

	$parentdir = basename(dirname($php_self));
	if ($view) {
		$code = '<script type="text/javascript" charset="utf-8" src="'.str_replace('/'.$parentdir,'',$options['url']).'js.php?view=';
		if ($view == 'article') {
			$msg = '调用文章代码';
			$code .= 'article';
			$code .= (empty($_POST['cate']) || !is_array($_POST['cate']) ? '' : '&cids='.implode('_',$_POST['cate'])). '&titlenum='.$_POST['titlenum'].'&titlelimit='.$_POST['titlelimit'].'&newwindow='.$_POST['newwindow'].'&cname='.$_POST['cname'].'&author='.$_POST['author'].'&orderby='.$orderby.'&dateline='.$_POST['dateline'].'&articleinfo='.$_POST['articleinfo'];
		} else {
			$msg = '调用统计信息代码';
			$code .= 'stat';
			$code .= '&showcate='.$_POST['showcate'].'&showarticle='.$_POST['showarticle'].'&showcomment='.$_POST['showcomment'].'&showtag='.$_POST['showtag'].'&showattach='.$_POST['showattach'].'&showtrack='.$_POST['showtrack'].'&showreguser='.$_POST['showreguser'].'&showtoday='.$_POST['showtoday'].'&showallviews='.$_POST['showallviews'];
		}
		$code .= "\"></script>";
	}
	$showcode = htmlspecialchars($code);
	$subnav = 'JS调用向导';
}

if ($action == 'doxml') {	
	  $str = '<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="../images/xsl/opml.xsl"?>
<!-- Generated by IXNA 0.5 -->
<opml version="2.0">
	<head>
		<title>IXNA OPML Feed</title>
		<dateCreated>' . $date . '</dateCreated>
	</head>	
	<body>';
  $query = $db->query("SELECT * FROM {$tablepre}xna_site WHERE state='1'");
while ($row = $db->row($query)) {
    $row[title] = htmlspecialchars($row[title]);
    $row[site_url] = htmlspecialchars($row[site_url]);
    $row[rss_url] = htmlspecialchars($row[rss_url]);
    $row[site_name] = htmlspecialchars($row[site_name]);
    $ret[] = $row;
    $str .= '<outline text="' . $row["title"] . '" content="' . $row["site_title"] .
      '" type="rss" htmlUrl="' . $row["site_url"] . '" xmlUrl="' . $row["rss_url"] .
      '" />';
  }
  $str .= '</body></opml>';
  $file = _ROOT . "/cache/opml.xml";
 	@ $fp = fopen($file, w);
		if (!$fp){
			echo "系统没有权限在网站cache目录生成opml.xml文件. <br />";
			echo "请修改根目录属性为777或者自己通过ftp创建time.txt文件. <br />";
			exit;
		}
		@fputs($fp, $str);
		fclose ($fp);
 
  $site_url = "http://" . $_SERVER["HTTP_HOST"];
  $file = _ROOT . "/sitemap.xml";
  //setting
  $site_freg = "weekly"; //"always", "hourly", "daily", "weekly", "monthly", "yearly" and "never".
  $cate_freg = "weekly";
  //
  $lastmodify = "filedate";
  switch ($lastmodify)  {
    case "now":
      $lastmod = date("Y-m-d");
      break;
    default:
      $lastmod = $lastmodify;
  }
  //header('Content-type: application/xml; charset="utf-8"',true);
  $str = '<?xml version="1.0" encoding="UTF-8"?>
		<?xml-stylesheet type="text/xsl" href="./images/xsl/sitemap.xsl"?>
			<!-- generator="ixna.net" -->
		<urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/09/sitemap.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
		   <url>
			  <loc>' . $site_url . '</loc>
			  <lastmod>' . DATE(DATE_ATOM) . '</lastmod>
			  <changefreq>' . $site_freg . '</changefreq>
			  <priority>1.0</priority>
		   </url>';
  $query = $db->query("SELECT feedid,feed_title,addtime FROM {$tablepre}xna_feed WHERE state!='0'");
	while ($row = $db->row($query)) {
		$addtime = DATE(DATE_ATOM,$row['addtime']);
		$url = $site_url . "/articles.php?id=" . $row['feedid'] . "";
		$str .= '<url>
			  <loc>' . $url . '</loc>
			  <lastmod>' . $addtime . '</lastmod>
			  <changefreq>' . $cate_freg . '</changefreq>
			  <priority>0</priority>
		      </url>';
  }
  $str .= '</urlset>';
 	@ $fp = fopen($file, w);
		if (!$fp){
			echo "系统没有权限在网站根目录生成sitemap.xml文件. <br />";
			echo "请修改根目录属性为777或者自己通过ftp创建sitemap.xml文件. <br />";
			exit;
		}
		@fputs($fp, $str);
		fclose ($fp);

  $file = _ROOT . "/news.xml";
  $strbaidu = '<?xml version="1.0" encoding="utf-8"?>
<!-- generator="ixna.net" -->
<document>
	<title>iDEA XML News Aggregator</title>
	<webSite>' . $site_url . '</webSite>
	<language>zh-cn</language>
	<generator>iXNA.Net</generator>
	<webMaster>spvrk@spvrk.com</webMaster>
	<updatePeri>15</updatePeri>
	';
  $query = $db->query("SELECT *  from {$tablepre}xna_feed WHERE state!='0' $arg  order by state desc,addtime desc");
	while ($row = $db->row($query)) {
    	$row["rss_cate"] = $rss_cate[$row["rss_cate"]];
    	$row[sum] = $xnum[$row[id]];
    	$row[addtime] = date("Y-m-d ",$row["addtime"]);

    	$strbaidu .= '<item>
		<title>' . $row["feed_title"] . '</title>
		<link>' . $row["feed_url"] . '</link>
		<description><![CDATA[' . $row["feed_content"] . ']]></description>
		<text></text>
		<category>' . $row["rss_cate"] . '</category>
		<image></image>
		<headlineImg></headlineImg>
		<keywords></keywords>
		<author><![CDATA[' . $row["site_name"] . ']]></author>
		<source>ixna.net</source>
		<pubDate>' . $row["addtime"] . '</pubDate>
		</item>';
  	}
	$strbaidu .= '</document>';
 	@ $fp = fopen($file, w);
		if (!$fp){
			echo "系统没有权限在网站根目录生成news.xml文件. <br />";
			echo "请修改根目录属性为777或者自己通过ftp创建news.xml文件. <br />";
			exit;
		}
		@fputs($fp, $strbaidu);
		fclose ($fp);

	redirect('已经生成静态文件.', 'index.php?job=cache&action=xml');
}

$navlink_L = ' &raquo; <a href="index.php?job=cache">系统维护</a>'.($subnav ? ' &raquo; '.$subnav : '');
include template("cache", _ROOT . "/template/admin/");
?>